package com.smedi.ismedi.authoritymanagement.core.port.adapter.persistence.repository.impl;

import com.smedi.ismedi.authoritymanagement.core.domain.repository.VerificationCodeRepository;
import com.smedi.ismedi.authoritymanagement.core.infrastructure.constant.ConstantField;
import com.smedi.ismedi.authoritymanagement.core.infrastructure.constant.CustomError;
import com.smedi.ismedi.cache.starter.util.RedisUtil;
import com.smedi.ismedi.web.starter.exception.LogicException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;

/**
 * @Author: xulinjun
 * @Date: 2021-7-13 9:37
 */
@Slf4j
@Repository
@AllArgsConstructor
public class VerificationCodeRepositoryImpl implements VerificationCodeRepository {
    private final RedisUtil redisUtil;

    @Override
    public Boolean hasMobileSession(String key) {
        return redisUtil.hasKey(key);
    }

    @Override
    public void deleteMobileSession(String key) {
        redisUtil.del(key);
    }

    @Override
    public void setResetPasswordSession(String key, String verificationCode, Long verificationCodeLive) {
        redisUtil.set(key, verificationCode, verificationCodeLive); // 设置有效期
    }

    @Override
    public void submit(String key, String verificationCode, String mobile) {
        if (redisUtil.hasKey(key)) {
            String reference = String.valueOf(redisUtil.get(key));
            if (!reference.equals(verificationCode)) {
                throw LogicException.raise(CustomError.INVALID_VERIFICATION_CODE);
            } else {
                // 失效已认证的验证码
                redisUtil.del(key);

                // 创建可更改数据的有效期
                key = ConstantField.waitingResetPasswordPath + mobile;
                redisUtil.set(key, LocalDateTime.now(), ConstantField.waitingResetPasswordLive);
            }
        } else {
            throw LogicException.raise(CustomError.VERIFICATION_CODE_OVERTIME);
        }
    }
}
